package com.sysassist.procmgr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.sysassist.R;
import com.sysassist.util.MyListAdapter;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;

public class ProcMgrActivity extends ListActivity {
	/** RunningAppProcessInfo List */
	private static List<RunningAppProcessInfo> procList = null;
	/** ApplicationInfo对象 */
	private PackageUtil packageUtil = null;
	/** 进度对话框 */
	private ProgressDialog pd = null;
	/** handle */
	private RefreshHandle handler = null;
	/** MyListAdapter */
	private MyListAdapter myListAdapter = null;
	/** AlertDialog in ListView */
	private AlertDialog itemDialog = null;
	/** ActivityManager */
	private ActivityManager activityManager = null;
	/** PackageManager */
	private PackageManager packageManager = null;

	private static final int MENU_CANCEL = 0;
	private static final int MENU_DETAIL = 1;
	private static final int MENU_KILL = 2;
	public static final String PROC_DETAIL_KEY = "com.sysassist.DetailProgramUtil";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.proc_list);
        
        procList = new ArrayList<RunningAppProcessInfo>();
        // 取得应用信息
    	packageUtil = new PackageUtil(this);
    	packageManager = packageUtil.getPm();
        // 取得进程信息
        getProcessInfo();

        // 关联layout中的ListView
        myListAdapter = showProcessInfo();
        
        setListAdapter(myListAdapter);
        
        /* 刷新按钮 */
        Button refresh = (Button) findViewById(R.id.refresh);
        refresh.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 刷新进程列表
				updateProcessList();
			}
		});
        
        /* ListView点击 */
        getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	@SuppressWarnings("unchecked")
			@Override
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		HashMap<String, Object> hm = (HashMap) parent.getItemAtPosition(position);
        		String proc_name = hm.get("proc_name").toString();
        		// 单击进程事件
        		showDialog(proc_name);
        	}
		});
    }
    
	/**
	 * 操作框显示
	 * @param proc_name
	 */
	private void showDialog(final String proc_name) {
		itemDialog = new AlertDialog.Builder(this).setItems(
				R.array.menu_task_operation, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
							// 返回
							case MENU_CANCEL: {
								return;
							}
							// 结束进程
							case MENU_KILL: {
								killProcess(proc_name);
								return;
							}
							// 查看详情
							case MENU_DETAIL: {
								turnToDetail(proc_name);
								return;
							}
						}

					}
				}).create();
		itemDialog.setTitle(R.string.menu_title);
		
//		itemDialog.setButton("关闭进程", new DialogInterface.OnClickListener(){
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				killProcess(proc_name);
//			}	
//		});
//		itemDialog.setButton2("查看详情", new DialogInterface.OnClickListener(){
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				// TODO Auto-generated method stub
//				
//			}	
//		});
		itemDialog.show();
	}
	
	/**
	 * showProcessInfo
	 * @return
	 */
    private MyListAdapter showProcessInfo() {
        List<HashMap<String,Object>> infoList = new ArrayList<HashMap<String,Object>>();
        // 获取CPU和内存信息
        ProcessMemoryUtil processMemoryUtil = new ProcessMemoryUtil();
        // 初始化所有进程的CPU和内存列表，用于检索每个进程的信息
        processMemoryUtil.initPMUtil();
		for (Iterator<RunningAppProcessInfo> iterator = procList.iterator(); iterator
				.hasNext();) {
			RunningAppProcessInfo procInfo = iterator.next();
            // 基本信息
			BasicProgramUtil basicProgram = buildProgramUtilSimpleInfo(
					processMemoryUtil, procInfo.pid, procInfo.processName);
			HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("proc_pic", basicProgram.getIcon());
            map.put("app_name", basicProgram.getProgramName());
            map.put("proc_name", basicProgram.getProcessName());
            map.put("mem_cpu", basicProgram.getCpuMemString());
            
            infoList.add(map);
        }

        // 关联layout中的ListView
		return new MyListAdapter(
                this, 
                infoList, 
                R.layout.proc_list_item,
                new String[]{"proc_pic", "app_name", "proc_name", "mem_cpu"},
                new int[]{R.id.proc_pic, R.id.app_name, R.id.proc_name, R.id.mem_cpu} );
    }
    
    /**
     * getProcessInfo
     * @return
     */
    private int getProcessInfo() {
        activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        procList = activityManager.getRunningAppProcesses();
        return procList.size();
    }
    
    /**
     * ActivityManager.RunningAppProcessInfo {
	 *     public int importance                // 进程在系统中的重要级别
	 *     public int importanceReasonCode        // 进程的重要原因代码
	 *     public ComponentName importanceReasonComponent    // 进程中组件的描述信息
	 *     public int importanceReasonPid        // 当前进程的子进程Id
	 *     public int lru                        // 在同一个重要级别内的附加排序值
	 *     public int pid                        // 当前进程Id
	 *     public String[] pkgList                // 被载入当前进程的所有包名
	 *     public String processName            // 当前进程的名称
	 *     public int uid                        // 当前进程的用户Id
     * }
     */
    
    /**
     * 结束进程
     * @param proc_name
     */
    private void killProcess(String proc_name) {
    	// 根据进程名，获取应用程序的ApplicationInfo对象
        ApplicationInfo tempAppInfo = packageUtil.getApplicationInfo(proc_name);
        // 结束进程
        activityManager.killBackgroundProcesses(tempAppInfo.packageName);
        // 刷新列表
        updateProcessList();
    }

    /**
     * 查看详情
     * @param proc_name
     */
	private void turnToDetail(String proc_name) {
		// 取得进程详细信息
		DetailProgramUtil detailProgramUtil = buildProgramUtilComplexInfo(proc_name);
		// 进程详情Activity
		Intent detailIntent = new Intent(ProcMgrActivity.this, ProcDetailActivity.class);
		Bundle mBundle = new Bundle();
		mBundle.putSerializable(PROC_DETAIL_KEY, detailProgramUtil);
		// 
		detailIntent.putExtras(mBundle);
		
		startActivity(detailIntent);
	}
	
    /**
     * 为进程获取基本的信息
     * @param procId
     * @param procNameString
     * @return
     */
	private BasicProgramUtil buildProgramUtilSimpleInfo(
			ProcessMemoryUtil processMemoryUtil, int procId, String procNameString) {
		BasicProgramUtil programUtil = new BasicProgramUtil();
    	// 进程名称
    	programUtil.setProcessName(procNameString);
    	
    	// 根据进程名，获取应用程序的ApplicationInfo对象
        ApplicationInfo tempAppInfo = packageUtil.getApplicationInfo(procNameString);

		if (tempAppInfo != null) {
			// 为进程加载图标和程序名称
			PackageManager packageManager = getApplicationContext().getPackageManager();
			programUtil.setIcon(tempAppInfo.loadIcon(packageManager));
			programUtil.setProgramName(tempAppInfo.loadLabel(packageManager).toString());
		} else {
			// 如果获取失败，则使用默认的图标和程序名
			programUtil.setIcon(getApplicationContext().getResources()
					.getDrawable(R.drawable.icon));
			programUtil.setProgramName(procNameString);
		}
		
		// 获取CPU内存信息
        String str = processMemoryUtil.getMemInfoByPid(procId);
        // 保存设定CPU内存信息
        programUtil.setCpuMemString(str);
        
    	return programUtil;
    }

    /**
     * 为进程获取安装包的详情
     * @param procNameString
     * @return
     */
    private DetailProgramUtil buildProgramUtilComplexInfo(String procNameString) {
        DetailProgramUtil complexProgramUtil = new DetailProgramUtil();
        // 根据进程名，获取应用程序的ApplicationInfo对象
        ApplicationInfo tempAppInfo = packageUtil.getApplicationInfo(procNameString);
        if (tempAppInfo == null) {
            return null;
        }
        
        PackageInfo tempPkgInfo = null;
        try {
            tempPkgInfo = packageManager.getPackageInfo(
                    tempAppInfo.packageName, 
                    PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_ACTIVITIES
                    | PackageManager.GET_SERVICES | PackageManager.GET_PERMISSIONS);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        if (tempPkgInfo == null) {
            return null;
        }
        
        complexProgramUtil.setProcessName(procNameString);
        complexProgramUtil.setCompanyName(getString(R.string.no_use));
        complexProgramUtil.setVersionName(tempPkgInfo.versionName);
        complexProgramUtil.setVersionCode(tempPkgInfo.versionCode);
        complexProgramUtil.setDataDir(tempAppInfo.dataDir);
        complexProgramUtil.setSourceDir(tempAppInfo.sourceDir);
        
        // 以下注释部分的信息暂时获取不到
//        complexProgramUtil.setFirstInstallTime(tempPkgInfo.firstInstallTime);
//        complexProgramUtil.setLastUpdateTime(tempPkgInfo.lastUpdateTime);
        
//        complexProgramUtil.setCodeSize(packageStats.codeSize);
//        complexProgramUtil.setDataSize(packageStats.dataSize);
//        complexProgramUtil.setCacheSize(packageStats.cacheSize);
//        complexProgramUtil.setExternalDataSize(0);
//        complexProgramUtil.setExternalCacheSize(0);
//        complexProgramUtil.setExternalMediaSize(0);
//        complexProgramUtil.setExternalObbSize(0);
        
        // 获取以下三个信息，需要为PackageManager进行授权(packageManager.getPackageInfo()方法)
        complexProgramUtil.setUserPermissions(tempPkgInfo.requestedPermissions);
        complexProgramUtil.setServices(tempPkgInfo.services);
        complexProgramUtil.setActivities(tempPkgInfo.activities);
        
        return complexProgramUtil;
    }
    
    /**
     * 进程列表的刷新
     */
    private void updateProcessList() {
    	// 标题上进度条显示
    	setProgressBarIndeterminateVisibility(true);
    	// 新建一个进度对话框，在更新列表时，覆盖在父视图之上
    	pd = new ProgressDialog(ProcMgrActivity.this);
    	pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	pd.setTitle(getString(R.string.progress_tips_title));
    	pd.setMessage(getString(R.string.progress_tips_content));
    	
    	// 启动新线程，执行更新列表操作
    	handler = new RefreshHandle();
    	RefreshThread thread = new RefreshThread();
    	thread.start();
    	
    	// 显示进度对话框
    	pd.show();
    }
    
    private class RefreshHandle extends Handler {
    	@Override
    	public void handleMessage(Message msg) {
    		setListAdapter(myListAdapter);
    		// 取消进度框
    		pd.dismiss();
    	}
    }
    
    /**
     * 更新列表线程
     * @author 278822
     *
     */
    private class RefreshThread extends Thread {
    	@Override
    	public void run() {
    		getProcessInfo();
    		myListAdapter = showProcessInfo();
    		Message msg = handler.obtainMessage();
    		handler.sendMessage(msg);
    	}
    }
}
